<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import StoreDialog from '../components/StoreDialog.vue'
import { API_CONFIG, STORE_API } from '../config/api.js'
import axios from 'axios'

// 门店数据
const stores = ref([])

// 搜索关键词
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentStore = ref({})

// 加载状态
const loading = ref(false)

// 获取门店列表
const fetchStores = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    }
    
    if (searchKeyword.value) {
      params.search = searchKeyword.value
    }
    
    const response = await axios.get(`${API_CONFIG.BASE_URL}${STORE_API.GET_STORES}`, { params })
    
    if (response.data.code === 200) {
      stores.value = response.data.data.stores
      total.value = response.data.data.pagination.total
    } else {
      ElMessage.error(response.data.message || '获取门店列表失败')
    }
  } catch (error) {
    console.error('获取门店列表失败:', error)
    ElMessage.error('获取门店列表失败')
  } finally {
    loading.value = false
  }
}

// 一键刷新员工数
const recalcStaffCounts = async () => {
  try {
    loading.value = true
    const response = await axios.post(`${API_CONFIG.BASE_URL}${STORE_API.RECALCULATE_STAFF_COUNTS}`)
    if (response.data.code === 200) {
      ElMessage.success(response.data.message || '员工数已刷新')
      await fetchStores()
    } else {
      ElMessage.error(response.data.message || '刷新失败')
    }
  } catch (error) {
    console.error('刷新员工数失败:', error)
    ElMessage.error('刷新员工数失败')
  } finally {
    loading.value = false
  }
}

// 总数据量
const total = ref(0)

// 处理添加门店
const handleAdd = () => {
  isEdit.value = false
  currentStore.value = {}
  dialogVisible.value = true
}

// 处理编辑门店
const handleEdit = (row) => {
  isEdit.value = true
  currentStore.value = { ...row }
  dialogVisible.value = true
}

// 处理删除门店
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除门店"${row.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    loading.value = true
    
    const response = await axios.delete(`${API_CONFIG.BASE_URL}${STORE_API.DELETE_STORE(row._id)}`)
    
    if (response.data.code === 200) {
      ElMessage.success('门店删除成功')
      fetchStores() // 重新获取列表
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除门店失败:', error)
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 处理表单提交
const handleSubmit = async (formData) => {
  loading.value = true
  
  try {
    if (isEdit.value) {
      // 更新门店
      const response = await axios.put(`${API_CONFIG.BASE_URL}${STORE_API.UPDATE_STORE(currentStore.value._id)}`, formData)
      
      if (response.data.code === 200) {
        ElMessage.success('门店更新成功')
        dialogVisible.value = false
        fetchStores() // 重新获取列表
      } else {
        ElMessage.error(response.data.message || '更新失败')
      }
    } else {
      // 添加门店
      const response = await axios.post(`${API_CONFIG.BASE_URL}${STORE_API.CREATE_STORE}`, formData)
      
      if (response.data.code === 201) {
        ElMessage.success('门店添加成功')
        dialogVisible.value = false
        fetchStores() // 重新获取列表
      } else {
        ElMessage.error(response.data.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchStores()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchStores()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchStores()
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  if (searchKeyword.value === '') {
    handleSearch()
  }
})

// 获取门店状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    '营业中': 'success',
    '暂停营业': 'warning',
    '装修中': 'info'
  }
  return statusMap[status] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    return dateString
  }
}



// 组件挂载时获取数据
onMounted(() => {
  fetchStores()
})
</script>

<template>
  <div class="manage-store-container">
    <div class="page-header">
      <h2>管理门店</h2>
      <p>管理所有门店信息，包括添加、编辑、删除门店，支持地图定位和地址搜索</p>
    </div>
    
    <div class="content-card">
      <div class="card-header">
        <div class="header-left">
          <h3>门店管理</h3>
          <el-button type="primary" size="small" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加门店
          </el-button>
        </div>
        
        <div class="header-right" style="display: flex; gap: 10px; align-items: center;">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索门店名称、地址或店长"
            size="small"
            style="width: 300px;"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-button type="success" size="small" @click="recalcStaffCounts" :loading="loading">
            刷新员工数
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table 
          :data="stores" 
          style="width: 100%" 
          border
          v-loading="loading"
          stripe
        >
          <el-table-column prop="name" label="门店名称" width="150" />
          <el-table-column prop="address" label="地址" width="250" show-overflow-tooltip />
          <el-table-column prop="phone" label="联系电话" width="150" />
          <el-table-column prop="manager" label="店长" width="120" />
          <el-table-column prop="staffCount" label="员工数" width="100" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="150" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>

              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    
    <!-- 门店编辑对话框 -->
    <StoreDialog
      v-model:visible="dialogVisible"
      :store-data="currentStore"
      :is-edit="isEdit"
      @submit="handleSubmit"
    />
  </div>
</template>

<style scoped>
.manage-store-container {
  min-height: calc(100vh - 140px);
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.content-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: calc(100vh - 200px);
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.table-container {
  padding: 20px;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .manage-store-container {
    padding: 10px;
  }
  
  .content-card {
    min-height: calc(100vh - 120px);
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-left {
    justify-content: space-between;
  }
  
  .header-right {
    width: 100%;
  }
  
  .header-right .el-input {
    width: 100% !important;
  }
  
  .table-container {
    padding: 10px;
  }
  
  .pagination-container {
    padding: 10px;
  }
}
</style>